package jnpf.property.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.property.entity.ZcglPropertyRepairEntity;
import jnpf.property.entity.ZcglPropertyRepairItemEntity;
import jnpf.property.mapper.ZcglPropertyRepairMapper;
import jnpf.property.model.zcglpropertyrepair.ZcglPropertyRepairForm;
import jnpf.property.model.zcglpropertyrepair.ZcglPropertyRepairPagination;
import jnpf.property.service.ZcglPropertyRepairItemService;
import jnpf.property.service.ZcglPropertyRepairService;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * ZcglPropertyRepair
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2024-11-14
 */
@Service
public class ZcglPropertyRepairServiceImpl extends ServiceImpl<ZcglPropertyRepairMapper, ZcglPropertyRepairEntity> implements ZcglPropertyRepairService {


        @Autowired
        private GeneraterSwapUtil generaterSwapUtil;

        @Autowired
        private UserProvider userProvider;

        @Autowired
        private AuthorizeService authorizeService;


    @Autowired
    private ZcglPropertyRepairItemService zcglPropertyRepairItemService;




    @Override
    public List<ZcglPropertyRepairEntity> getList(ZcglPropertyRepairPagination zcglPropertyRepairPagination){
        return getTypeList(zcglPropertyRepairPagination,zcglPropertyRepairPagination.getDataType());
    }
    @Override
    public List<ZcglPropertyRepairEntity> getTypeList(ZcglPropertyRepairPagination zcglPropertyRepairPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
		List<List<String>> intersectionList =new ArrayList<>();
		int total=0;
		int zcglPropertyRepairNum =0;
        QueryWrapper<ZcglPropertyRepairEntity> zcglPropertyRepairQueryWrapper=new QueryWrapper<>();
		int zcglPropertyRepairItemNum =0;
        QueryWrapper<ZcglPropertyRepairItemEntity> zcglPropertyRepairItemQueryWrapper=new QueryWrapper<>();
            long zcglPropertyRepairItemcount = zcglPropertyRepairItemService.count();
		List<String> allSuperIDlist = new ArrayList<>();
		String superOp ="";
	if (ObjectUtil.isNotEmpty(zcglPropertyRepairPagination.getSuperQueryJson())){
		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcglPropertyRepairPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
		String matchLogic = superQueryJsonModel.getMatchLogic();
		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
		for (ConditionJsonModel conditionjson : superQueryList){
            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
		    if (map.get("multiple") != null) {
		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
		            conditionjson.setFieldValue("[]");
		        }
		    }
            conditionjson.setTableName(tableName);
		}
		List<String> allSuperList = new ArrayList<>();
		List<List<String>> intersectionSuperList  = new ArrayList<>();
        int zcglPropertyRepairNum1 = 0;
        QueryWrapper<ZcglPropertyRepairEntity> zcglPropertyRepairSuperWrapper = new QueryWrapper<>();
        zcglPropertyRepairNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglPropertyRepairSuperWrapper,superQueryList,matchLogic,"zcglPropertyRepair")
        ,new ZcglPropertyRepairEntity(),zcglPropertyRepairNum1);
            if (zcglPropertyRepairNum1>0){
            List<String> zcglPropertyRepairList =this.list(zcglPropertyRepairSuperWrapper).stream().map(ZcglPropertyRepairEntity::getId).collect(Collectors.toList());
            allSuperList.addAll(zcglPropertyRepairList);
            intersectionSuperList.add(zcglPropertyRepairList);
            }
        int zcglPropertyRepairItemNum1 = 0;
        QueryWrapper<ZcglPropertyRepairItemEntity> zcglPropertyRepairItemSuperWrapper = new QueryWrapper<>();
        zcglPropertyRepairItemNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglPropertyRepairItemSuperWrapper,superQueryList,matchLogic,"zcglPropertyRepairItem")
        ,new ZcglPropertyRepairItemEntity(),zcglPropertyRepairItemNum1);
            if (zcglPropertyRepairItemNum1>0 && zcglPropertyRepairItemcount>0){
            List<String> zcglPropertyRepairItemList =zcglPropertyRepairItemService.list(zcglPropertyRepairItemSuperWrapper).stream().map(ZcglPropertyRepairItemEntity::getParentid).collect(Collectors.toList());
            allSuperList.addAll(zcglPropertyRepairItemList);
            intersectionSuperList.add(zcglPropertyRepairItemList);
            }
		superOp = matchLogic;
		//and or
		if(matchLogic.equalsIgnoreCase("and")){
		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
		}else{
		    allSuperIDlist = allSuperList;
		}
    }
    boolean pcPermission = false;
    boolean appPermission = false;
    boolean	isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
    if(isPc && pcPermission){
		if (!userProvider.get().getIsAdministrator()){
				Object zcglPropertyRepairObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglPropertyRepairQueryWrapper,zcglPropertyRepairPagination.getMenuId(),"zcgl_property_repair"));
            if (ObjectUtil.isEmpty(zcglPropertyRepairObj)){
                return new ArrayList<>();
            } else {
                zcglPropertyRepairQueryWrapper = (QueryWrapper<ZcglPropertyRepairEntity>)zcglPropertyRepairObj;
                zcglPropertyRepairNum++;
            }
				Object zcglPropertyRepairItemObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglPropertyRepairItemQueryWrapper,zcglPropertyRepairPagination.getMenuId(),"zcgl_property_repair_item"));
            if (ObjectUtil.isEmpty(zcglPropertyRepairItemObj)){
                return new ArrayList<>();
            } else {
                zcglPropertyRepairItemQueryWrapper = (QueryWrapper<ZcglPropertyRepairItemEntity>)zcglPropertyRepairItemObj;
                zcglPropertyRepairItemNum++;
            }
        }
    }
    if(!isPc && appPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object zcglPropertyRepairObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglPropertyRepairQueryWrapper,zcglPropertyRepairPagination.getMenuId(),"zcglPropertyRepair"));
            if (ObjectUtil.isEmpty(zcglPropertyRepairObj)){
                return new ArrayList<>();
            } else {
            zcglPropertyRepairQueryWrapper = (QueryWrapper<ZcglPropertyRepairEntity>)zcglPropertyRepairObj;
            zcglPropertyRepairNum++;
			}


			Object zcglPropertyRepairItemObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglPropertyRepairItemQueryWrapper,zcglPropertyRepairPagination.getMenuId(),"zcglPropertyRepairItem"));
            if (ObjectUtil.isEmpty(zcglPropertyRepairItemObj)){
                return new ArrayList<>();
            } else {
            zcglPropertyRepairItemQueryWrapper = (QueryWrapper<ZcglPropertyRepairItemEntity>)zcglPropertyRepairItemObj;
            zcglPropertyRepairItemNum++;
			}


		}
    }
        if(isPc){
			if(ObjectUtil.isNotEmpty(zcglPropertyRepairPagination.getRepairAddress())){
            zcglPropertyRepairNum++;
            zcglPropertyRepairQueryWrapper.lambda().like(ZcglPropertyRepairEntity::getRepairAddress,zcglPropertyRepairPagination.getRepairAddress());
                    }

			if(ObjectUtil.isNotEmpty(zcglPropertyRepairPagination.getApplicantUser())){
            zcglPropertyRepairNum++;
            List ApplicantUserList =  JsonUtil.getJsonToList(zcglPropertyRepairPagination.getApplicantUser(),String.class);
            String fir = String.valueOf(ApplicantUserList.get(0));
            String sec = String.valueOf(ApplicantUserList.get(1));
            zcglPropertyRepairQueryWrapper.lambda().ge(ZcglPropertyRepairEntity::getApplicantUser, fir)
            .le(ZcglPropertyRepairEntity::getApplicantUser, sec);

                    }

			if(ObjectUtil.isNotEmpty(zcglPropertyRepairPagination.getProjectId())){
            zcglPropertyRepairNum++;
                zcglPropertyRepairQueryWrapper.lambda().eq(ZcglPropertyRepairEntity::getProjectId,zcglPropertyRepairPagination.getProjectId());
                    }

			if(ObjectUtil.isNotEmpty(zcglPropertyRepairPagination.getAssetId())){
            zcglPropertyRepairNum++;
                zcglPropertyRepairQueryWrapper.lambda().eq(ZcglPropertyRepairEntity::getAssetId,zcglPropertyRepairPagination.getAssetId());
                    }

        }
            if(zcglPropertyRepairItemNum>0){
            List<String> zcglPropertyRepairItemIdList = zcglPropertyRepairItemService.list(zcglPropertyRepairItemQueryWrapper).stream().filter(t->StringUtil.isNotEmpty(t.getParentid())).map(t->t.getParentid()).collect(Collectors.toList());
			long count = zcglPropertyRepairItemService.count();
            if (count>0){
				intersectionList.add(zcglPropertyRepairItemIdList);
            }
            AllIdList.addAll(zcglPropertyRepairItemIdList);
            }
            total+=zcglPropertyRepairItemNum;
		List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
		if (total>0){
		if (intersection.size()==0){
		    intersection.add("jnpfNullList");
		}
         zcglPropertyRepairQueryWrapper.lambda().in(ZcglPropertyRepairEntity::getId, intersection);
		}
        //是否有高级查询
		if (StringUtil.isNotEmpty(superOp)){
		    if (allSuperIDlist.size()==0){
		        allSuperIDlist.add("jnpfNullList");
		    }
		List<String> finalAllSuperIDlist = allSuperIDlist;
            zcglPropertyRepairQueryWrapper.lambda().and(t->t.in(ZcglPropertyRepairEntity::getId, finalAllSuperIDlist));
		}

        //排序
        if(StringUtil.isEmpty(zcglPropertyRepairPagination.getSidx())){
        zcglPropertyRepairQueryWrapper.lambda().orderByDesc(ZcglPropertyRepairEntity::getId);
        }else{
            try {
            	String sidx = zcglPropertyRepairPagination.getSidx();
                ZcglPropertyRepairEntity zcglPropertyRepairEntity = new ZcglPropertyRepairEntity();
				Field declaredField = zcglPropertyRepairEntity.getClass().getDeclaredField(sidx);
				declaredField.setAccessible(true);
				String value = declaredField.getAnnotation(TableField.class).value();
                 zcglPropertyRepairQueryWrapper="asc".equals(zcglPropertyRepairPagination.getSort().toLowerCase())?zcglPropertyRepairQueryWrapper.orderByAsc(value):zcglPropertyRepairQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<ZcglPropertyRepairEntity> page=new Page<>(zcglPropertyRepairPagination.getCurrentPage(), zcglPropertyRepairPagination.getPageSize());
                IPage<ZcglPropertyRepairEntity> userIPage=this.page(page, zcglPropertyRepairQueryWrapper);
                return zcglPropertyRepairPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<ZcglPropertyRepairEntity> list = new ArrayList();
                return zcglPropertyRepairPagination.setData(list, list.size());
            }
        }else{
            return this.list(zcglPropertyRepairQueryWrapper);
        }
    }


    @Override
    public ZcglPropertyRepairEntity getInfo(String id){
        QueryWrapper<ZcglPropertyRepairEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcglPropertyRepairEntity::getId,id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcglPropertyRepairEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcglPropertyRepairEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ZcglPropertyRepairEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法
		@Override
		public List<ZcglPropertyRepairItemEntity> getZcglPropertyRepairItemList(String id,ZcglPropertyRepairPagination zcglPropertyRepairPagination){
				QueryWrapper<ZcglPropertyRepairItemEntity> queryWrapper = new QueryWrapper<>();
				queryWrapper = zcglPropertyRepairItemService.getChild(zcglPropertyRepairPagination,queryWrapper);
				queryWrapper.lambda().eq(ZcglPropertyRepairItemEntity::getParentid, id);
				return zcglPropertyRepairItemService.list(queryWrapper);
				}

		@Override
		public List<ZcglPropertyRepairItemEntity> getZcglPropertyRepairItemList(String id){
				QueryWrapper<ZcglPropertyRepairItemEntity> queryWrapper = new QueryWrapper<>();
				queryWrapper.lambda().eq(ZcglPropertyRepairItemEntity::getParentid, id);
				return zcglPropertyRepairItemService.list(queryWrapper);
        }

    //列表子表数据方法



    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcglPropertyRepairForm form, int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		if (isUp){
			 id = form.getId();
		}
				 if (form.getZcglpropertyrepairitemList()!=null){
         }
        if (total>0){
        return true;
        }
        return false ;
    }


}
